<template>
  <div class="box">
    <GoodInfo :isCheckAll="isCheckAll" @changeAllStatus="changeAllStatus" />
    <ul>
      <!-- vue框架中：属性名=true，属性值是布尔值来决定是否显示此属性 -->
      <GoodItem v-for="good in goods" :key="good.id" :good="good" @deleteGood="deleteGood"
        @changeCheckStatus="changeCheckStatus" @changeNum="changeNum" />
    </ul>
    <Empty v-if="goods.length === 0" />
    <CarFooter v-if="goods.length > 0" :goods="goods" @deleteSelectedGood="deleteSelectedGood" />
  </div>
</template>

<script setup>
import GoodItem from './GoodItem.vue';
import Empty from './Empty.vue'
import CarFooter from './CarFooter.vue';
import GoodInfo from './GoodInfo.vue';
import { ref, computed } from 'vue'

// 数据源
const goods = ref([
  {
    id: 1,
    isCheck: true,
    goodName: 'iphone6',
    price: 800,
    number: 10,
  },
  {
    id: 2,
    isCheck: false,
    goodName: '华为meta70',
    price: 1000,
    number: 11,
  },
  {
    id: 3,
    isCheck: true,
    goodName: '华为meta80',
    price: 1200,
    number: 12,
  },
  {
    id: 4,
    isCheck: false,
    goodName: '华为meta90',
    price: 1400,
    number: 13,
  },
])

// 计算出是否全都选中
const isCheckAll = computed(() => {
  return goods.value.every(good => good.isCheck) && (goods.value.length > 0)
})

// 删除所选商品
const deleteSelectedGood = () => {
  if (!confirm('确认删除吗')) {
    return
  }
  goods.value = goods.value.filter(good => !good.isCheck)
}

// 删除商品
const deleteGood = (id) => {
  let good = goods.value.find(good => good.id === id)
  if (!confirm(`确认删除[${good.goodName}]吗`)) {
    return
  }

  goods.value = goods.value.filter(good => good.id !== id)
}

// 改变商品的选中状态
const changeCheckStatus = (id) => {
  console.log('父', id)
  // // 方案1：
  // let index = goods.value.findIndex(good => good.id === id)
  // goods.value[index].isCheck = !goods.value[index].isCheck

  // 方案1：
  goods.value = goods.value.map(good => {
    if (good.id === id) {
      good.isCheck = !good.isCheck
    }
    return good
  })


}

// 改变商品的数量
const changeNum = (id, flag) => {
  // flag: inc 、dec
  console.log('父', id, flag)
  goods.value = goods.value.map(good => {
    if (good.id === id) {
      if (flag === 'inc') {
        good.number += 1
      } else {
        good.number -= 1
      }
    }
    return good
  })

}

// 改变所有商品选中状态
const changeAllStatus = (bool) => {
  console.log('父', bool)
  goods.value = goods.value.map(good => {
    good.isCheck = bool
    return good
  })
}

</script>


<style>
* {
  padding: 0;
  margin: 0;
}

.box {
  width: 600px;
  border: 2px solid red;
  margin: 50px auto;
}
</style>